import Vue from 'vue'
import App from './App'
import Request from 'luch-request'

const http = new Request();

http.setConfig((config) => {
	config.baseURL = 'https://netease-cloud-music-api-omega-black.vercel.app';

	return config;
})

uni.kHttp = http;

/**
 * @description 科学计数处理播放量
 * @param {Object} count 播放量
 */
uni.kHandlePlayCount = function(count) {
	if (count > 99999999) {
		let m100 = Math.floor(count / 100000000);
		let m10 = Math.floor((count - m100 * 100000000) / 10000000);
		return m100 + '.' + m10 + '亿';
	}
	return Math.floor(count / 10000) + '万';
}

/**
 * @description 秒转换
 * @param {Object} value
 */
uni.kFormatSeconds = function(value) {
	let result = parseInt(value)
	let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
	let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 %
		60));
	let s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));

	let res = '';
	if (h !== '00') res += `${h}:`;
	if (m !== '00') res += `${m}:`;
	res += `${s}`;
	
	res = res < 60 ? '00:' + res : res;
	return res;
}

/**
 * @description 函数节流
 */
uni.kThrottle = function(fn, interval) {
	var enterTime = 0; // 触发的时间
	var gapTime = interval || 500; // 间隔时间，如果interval不传，则默认300ms
	return function() {
		var context = this;
		var backTime = new Date(); // 第一次函数return即触发的时间
		// console.log(uni.store.state);
		if (backTime - enterTime > gapTime) {
			fn.call(context, arguments);
			enterTime = backTime; // 赋值给第一次触发的时间，这样就保存了第二次触发的时间
		}
	}
}

/**
 * @description 函数防抖
 */
uni.kDebounce = function(fn, interval) {
	var timer;
	var gapTime = interval || 1000; // 间隔时间，如果interval不传，则默认1000ms

	return function() {
		clearTimeout(timer);
		var context = this;
		var args = arguments; // 保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的

		timer = setTimeout(function() {
			fn.call(context, args);
		}, gapTime);
	}
}

uni.kGetImgPrimaryColor = function(src, index, debug = true, w = 100, h = 100, r = 5) {
	if (debug) console.log(src, 'src');
	const ctx = uni.createCanvasContext('myCanvas' + index);
	const that = this;
	const img_w = w;
	const img_h = h;
	const img_r = r;

	const COLOR_SIZE =
	40; // 单位色块的大小（像素个数，默认40）。以单位色块的平均像素值作为统计单位 参考：https://blog.csdn.net/Elle_Peng/article/details/105138504
	const LEVEL = 32; // 色深，颜色区分参数（0-255），总256，2^8，即8bit，4个通道（rgba），即默认色深4*8bit，32bit
	// 获取每段的颜色数据
	// 根据像素数据，按单位色块进行切割
	const getLevelData = function(imageData) {
		const len = imageData.length;
		const mapData = {};
		for (let i = 0; i < len; i += COLOR_SIZE * 4) {
			const blockColor = getBlockColor(imageData, i); // 该区块平均rgba [{r, g, b, a}]数据
			// 获取各个区块的平均rgba数据，将各个通道的颜色进行LEVEL色深降级
			// 根据r_g_b_a 建立map索引
			const key = getColorLevel(blockColor);
			!mapData[key] && (mapData[key] = []);
			mapData[key].push(blockColor);
		}
		return mapData;
	}
	// 获取单位块的全部色值
	// 并根据全部色值，计算平均色值
	// 处理最后边界值，小于COLOR_SIZE
	const getBlockColor = function(imageData, start) {
		let data = [],
			count = COLOR_SIZE,
			len = COLOR_SIZE * 4;
		imageData.length <= start + len && (count = Math.floor(imageData.length - start - 1) / 4);
		for (let i = 0; i < count; i += 4) {
			data.push({
				r: imageData[start + i + 0],
				g: imageData[start + i + 1],
				b: imageData[start + i + 2],
				a: imageData[start + i + 3]
			})
		}
		return getAverageColor(data);
	}
	// 取出各个通道的平均值，即为改色块的平均色值
	const getAverageColor = function(colorArr) {
		const len = colorArr.length;
		let sr = 0,
			sg = 0,
			sb = 0,
			sa = 0;
		colorArr.map(function(item) {
			sr += item.r;
			sg += item.g;
			sb += item.b;
			sa += item.a;
		});
		return {
			r: Math.round(sr / len),
			g: Math.round(sg / len),
			b: Math.round(sb / len),
			a: Math.round(sa / len)
		}
	}
	// 获取色深级别
	const getColorLevel = function(color) {
		return getLevel(color.r) + '_' + getLevel(color.g) + '_' + getLevel(color.b) + '_' + getLevel(color.a);
	}
	// 色深降级
	const getLevel = function(value) {
		return Math.round(value / LEVEL);
	}
	// 根据色块，获取主色调
	const getMostColor = function(colorData) {
		let rst = null,
			len = 0;
		for (let key in colorData) {
			// console.log('colorData[key].length', colorData[key].length)
			// console.log('colorData[key].length', colorData[key])
			// console.log('colorData[key].length', key)
			colorData[key].length > len && (
				rst = colorData[key],
				len = colorData[key].length
			)
		}
		return rst;
	}
	return new Promise(function(resove, reject) {
		uni.getImageInfo({
			src: src,
			success: (res) => {
				if (debug) console.log(res, '图片信息');
				// console.log(res, '图片信息');
				const poster = res.path;
				// 绘制背景图片圆角
				let bg_x = 0; // 图片的x坐标
				let bg_y = 0; // 图片的y坐标
				let bg_w = img_w; // 图片的宽度
				let bg_h = img_h; // 图片的高度
				let bg_r = img_r; // 图片的圆角
				ctx.save();
				ctx.beginPath();
				ctx.setFillStyle('transparent');
				// 左上角
				ctx.arc(bg_x + bg_r, bg_y + bg_r, bg_r, Math.PI, Math.PI * 1.5);
				// border-top
				ctx.moveTo(bg_x + bg_r, bg_y);
				ctx.lineTo(bg_x + bg_w - bg_r, bg_y);
				ctx.lineTo(bg_x + bg_w, bg_y + bg_r);
				// 右上角
				ctx.arc(bg_x + bg_w - bg_r, bg_y + bg_r, bg_r, Math.PI * 1.5, Math.PI * 2);
				// border-right
				ctx.lineTo(bg_x + bg_w, bg_y + bg_h - bg_r);
				ctx.lineTo(bg_x + bg_w - bg_r, bg_y + bg_h);
				// 右下角
				ctx.arc(bg_x + bg_w - bg_r, bg_y + bg_h - bg_r, bg_r, 0, Math.PI * 0.5);
				// border-bottom
				ctx.lineTo(bg_x + bg_r, bg_y + bg_h);
				ctx.lineTo(bg_x, bg_y + bg_h - bg_r);
				// 左下角
				ctx.arc(bg_x + bg_r, bg_y + bg_h - bg_r, bg_r, Math.PI * 0.5, Math.PI);
				// border-left
				ctx.lineTo(bg_x, bg_y + bg_r);
				ctx.lineTo(bg_x + bg_r, bg_y);
				// ctx.arc(bg_w / 2 + bg_x, bg_h / 2 + bg_y, bg_w / 2, 0, Math.PI * 2, false);
				ctx.fill();
				ctx.closePath();
				ctx.clip();
				ctx.drawImage(poster, bg_x, bg_y, bg_w, bg_h);
				ctx.restore();
				ctx.draw(false, () => {
					uni.canvasToTempFilePath({
						x: 0,
						y: 0,
						width: bg_w,
						height: bg_h,
						canvasId: 'myCanvas' + index,
						success: (canvasRes) => {
							if (debug) console.log(src, '图片路径');
							let tempPath = canvasRes.tempFilePath;
							// 获取canvas区域隐含的像素数据
							uni.canvasGetImageData({
								canvasId: 'myCanvas' + index,
								x: 0,
								y: 0,
								width: bg_w,
								height: bg_h,
								success: (getImgRes) => {
									// console.log(getImgRes, '图片像素信息');
									const imageData = getImgRes
										.data;
									// getLevelData(imageData);
									const mapData =
										getLevelData(imageData);
									const colors = getMostColor(
										mapData);
									if (!colors) {
										reject({
											r: '255',
											g: '255',
											b: '255'
										})
									} else {
										const color =
											getAverageColor(
												colors);
										// console.log(color);
										resove(color);
									}
									if (debug) console.log(
										colors);
									// console.log(imageData[imageData.length / 2]);
									if (debug) console.log((
											imageData[
												imageData
												.length / 2
												] + ',' +
											imageData[
												imageData
												.length /
												2 + 1] +
											',' + imageData[
												imageData
												.length /
												2 + 2]),
										'图片主色');
									const rgb =
										`rgba(${imageData[imageData.length / 2]}, ${imageData[imageData.length / 2] + 1}, ${imageData[imageData.length / 2 + 2]}, 1)`;
									resove({
										r: imageData[
											imageData
											.length /
											2],
										g: imageData[
											imageData
											.length /
											2] + 1,
										b: imageData[
											imageData
											.length /
											2] + 2
									});
									// 分区块，可以拓展性的求主要色板，用来做palette
									// let resImageObj = getMainColot
								}
							})
						},
						fail: (canvasErr) => {
							if (debug) console.log(canvasErr, 'canvasErr');
							reject(canvasErr);
						}
					})
				})
			},
			fail: (err) => {
				if (debug) console.log(err, '获取图片信息失败');
				reject(err);
			}
		})
	})
}

Vue.config.productionTip = false

import {
	router,
	RouterMount
} from './router.js'
uni.kRouter = router;

Vue.use(router);

App.mpType = 'app'

const app = new Vue({
	...App
})
// #ifdef H5
RouterMount(app, router, '#app');
// #endif
// #ifndef H5
app.$mount();
// #endif
